package com.zrm.zfcrpa.configuration.security;

import com.zrm.zfcrpa.configuration.security.mobile.SmsCodeAuthConfig;
import com.zrm.zfcrpa.dao.mapper.loginMapper.LoginDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@PropertySource("classpath:application-hdev.yml")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${notFilterUrl}")
    public String[] URL_ARRAYS;

    @Autowired
    private MyUserDetals myUserDetals;

    @Autowired
    private SmsCodeAuthConfig smsCodeAuthConfig;

    @Autowired
    private MyAuthenticationEntryPoint myAuthenticationEntryPoint;

    @Autowired
    private LoginDao loginDao;

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetals);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
       http.csrf().disable().cors()
               .and()
               .addFilterBefore(new MyTokenFilter(authenticationManager(),loginDao), UsernamePasswordAuthenticationFilter.class)
               .addFilterBefore(new MyTokenAuthFilter(authenticationManager()), BasicAuthenticationFilter.class)
               .authorizeRequests()
               .antMatchers(URL_ARRAYS).permitAll()
               .anyRequest().authenticated()
               .and()
               .exceptionHandling()
               .authenticationEntryPoint(myAuthenticationEntryPoint)
               .and()
               .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
       http.apply(smsCodeAuthConfig);
    }
}
